<template>
  <div class="page-register">
    <article class="header">
      <header>
        <a href="/"
           class="site-logo" />
        <span class="login">
          <em class="bold">已有美团账号?</em>
          <a href="/login">
            <el-button type="primary"
                       size="small">登录</el-button>
          </a>
        </span>
      </header>
    </article>
    <section>

      <el-form :model="registerForm"
               ref="registerForm"
               status-icon
               label-width="80px"
               class="demo-ruleForm"
               :rules='registerRules'>
        <el-form-item label="昵称"
                      prop="name">
          <el-input v-model="registerForm.name" />
        </el-form-item>
        <el-form-item prop="email"
                      label="邮箱">
          <el-input v-model="registerForm.email"></el-input>
          <el-button size="mini"
                     @click="sendMsg"> {{ statusMsg }}
          </el-button>
          <span class="status">{{ emailMsg }}</span>
        </el-form-item>
        <el-form-item label="验证码"
                      prop="code">
          <el-input v-model="registerForm.code"
                    maxlength="4" />
        </el-form-item>
        <el-form-item label="密码"
                      prop="pwd">
          <el-input v-model="registerForm.pwd"
                    type="password"
                    autocomplete="off" />
        </el-form-item>
        <el-form-item label="确认密码"
                      prop="cpwd">
          <el-input v-model="registerForm.cpwd"
                    type="password"
                    autocomplete="off" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary"
                     @click="register">同意以下协议并注册
          </el-button>
          <div class="error">{{ errormsg }}</div>
        </el-form-item>
        <el-form-item>
          <a class="f1"
             href="http://www.meituan.com/about/terms"
             target="_blank">《美团网用户协议》</a>
        </el-form-item>
      </el-form>
    </section>

  </div>
</template>
 
<script lang='ts'>
// 邮箱验证
import { Component, Vue } from "vue-property-decorator";
import { ElTree } from "element-ui/types/tree";
import CryptoJS from "crypto-js";
@Component({
  layout: "blank"
})
export default class extends Vue {
  $refs!: {
    tree: ElTree;
  };

  // 表单
  registerForm: any = {
    name: "",
    email: "",
    code: "",
    pwd: "",
    cpwd: ""
  };
  // 验证码相关
  is_send: boolean = false;
  sendTimer: number = null;
  sendNum: number = 60;
  emailMsg: string = "";
  // 注册失败信息
  errormsg: string = "";
  // 表单验证
  registerRules: object = {
    name: [
      { required: true, message: "请输入昵称", trigger: "blur" },
      { min: 3, max: 18, message: "长度在 3 到 18 个字符", trigger: "blur" }
    ],
    email: [
      { required: true, message: "请输入邮箱地址", trigger: "blur" },
      {
        type: "email",
        message: "请输入正确的邮箱地址",
        trigger: ["blur"]
      }
    ],
    code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
    pwd: [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 6, max: 8, message: "长度在 6 到 8 个字符", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          // this.$refs.registerForm.validateField("cpwd");
          callback();
        },
        trigger: "blur"
      }
    ],
    cpwd: [
      { required: true, message: "请再次输入密码", trigger: "blur" },
      {
        validator: (rule, value, callback) => {
          if (value !== this.registerForm["pwd"]) {
            callback("两次输入密码不一致!");
          } else {
            callback();
          }
        },
        trigger: "blur"
      }
    ]
  };

  // 发送验证码
  async sendMsg() {
    if (this.sendTimer) return false;
    // 只校验 name email
    let namePass, emailPass;
    // 校验单个
    this.$refs["registerForm"]["validateField"]("name", vaild => {
      namePass = vaild;
    });
    this.$refs["registerForm"]["validateField"]("email", vaild => {
      emailPass = vaild;
    });
    if (!namePass && !emailPass) {
      const { status, data } = await this["$axios"].post("/users/verify", {
        username: this.registerForm["name"],
        email: this.registerForm["email"]
      });
      if (status === 200 && data.code === 0) {
        this.is_send = true;
        this.sendTimer = setInterval(() => {
          this.sendNum--;
          if (this.sendNum === 0) {
            clearInterval(this.sendTimer);
            this.is_send = false;
          }
        }, 1000);
      } else {
        this.emailMsg = data.msg;
      }
    }
  }
  // 显示
  get statusMsg() {
    return this.is_send ? `验证码已发送,${this.sendNum}s` : `发送验证码`;
  }
  // 注册
  register(): void {
    // 校验所有规则是否通过
    console.log(this.registerForm.pwd)
    this.$refs["registerForm"]["validate"](valid => {
      if (valid) {
        this["$axios"]
          .post("/users/signup", {
            // 用户名可能是中文 处理中文(防止乱码)
            username: window['encodeURIComponent'](this.registerForm.name),
            // MD5加密 crypto-js
            password: CryptoJS.MD5(this.registerForm.pwd).toString(),
            email: this.registerForm.email,
            code: this.registerForm.code
          })
          .then(({ status, data }) => {
            if (status === 200) {
              if (data && data.code === 0) {
                // 注册成功
                this["$message"]({
                  message: "注册成功",
                  type: "success",
                  onClose: () => {
                    this.$router.push('/login')
                  }
                });
              } else {
                this.errormsg = data.msg;
              }
            } else {
              this.errormsg = `服务器异常,code: ${status}`;
            }
          });
      }
    });
  }
}
</script>
<style lang='scss' >
@import "@/assets/css/register/index.scss";
</style>